<?php

namespace App\GraphQL\Mutations\Device;

use App\Models\Device;
use App\Models\DeviceOrder;
use App\Models\Group;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class Activation
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $id = $args['id'];
        $data = $args['input'];
        $device = $this->validate($id, $data);
        $data['status'] = 'IDLE';
        $device->update($data);
        return [
            'status'=> '200',
            'message'=>'激活成功'
        ];
    }
    public function validate($id,$data){
        $rules = [
            'device_group_id' => [
                'required'
            ],
            'device_order_id' => [
                'required'
            ]
        ];
        $messages = [
            'device_group_id.required' => '设备分组不能为空',
            'device_order_id.required' => '设备订单不能为空',
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        if(!DeviceOrder::find($data['device_order_id'])){
            throw new \Exception('订单不存在!');
        }
        if(!Group::find($data['device_group_id'])){
            throw new \Exception('设备分组不存在!');
        }
        $old = Device::find($id);
        if($old->status === 'DORMANT'){
            throw new \Exception('设备状态不正确!');
        }
        if (!$old){
            throw new \Exception('设备不存在!');
        }
        return $old;
    }
}
